﻿// 暂时无用 暂留

//using System.Data.SqlTypes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Unis.Framework.Core.Exceptions;
using Unis.Framework.Core.Infrastructure;
using Unis.Framework.Core.Log;
using Unis.Framework.Core.Utility;
using Unis.Framework.ORM.Attributes;
using Unis.Framework.ORM.BaseDefiniens.Enums;
using Unis.Framework.ORM.Common;
using Unis.Framework.ORM.DbSql;
using Unis.Framework.ORM.Mapping;
using Unis.Framework.ORM.Model;
using Unis.Framework.ORM.Persistence;
using Unis.Framework.ORM.Xml;
using Unis.Framework.RuleBase.Attributes;
using Unis.Framework.RuleBase.Exceptions;
using Unis.ORM.Common;
using Unis.ORM.Mapping;
using Unis.ORM.Persistence;
using Unis.ORM.Xml;
using Unis.RuleBase.Common;
using Unis.RuleBase.Exceptions;
using Unis.RuleBase.IFace;

namespace Unis.Framework.RuleBase.Common
{
    public class ObjectEditHelper
    {
        // Methods
        public OperationType ConvertEntityStateToOperationType(EntityState dataState)
        {
            switch (dataState)
            {
                case EntityState.New:
                    return OperationType.Insert;

                case EntityState.Modified:
                    return OperationType.Update;

                case EntityState.Deleted:
                    return OperationType.Delete;
            }
            return OperationType.None;
        }

        public IList<EntityDbCommandInfo> CreateCmdsFromDataSet(Database db, IBaseRule baseRule, DataSet dsData, object foreingKeyValue, object dataInDocType)
        {
            List<EntityDbCommandInfo> list = new List<EntityDbCommandInfo>();
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            OperationType optTypes = OperationType.Update | OperationType.Insert;
            if (objectDataMappingAttribute.DeleteNotInIds)
            {
                optTypes |= OperationType.DeleteNotIn;
            }
            else
            {
                optTypes |= OperationType.Delete;
            }
            PersistenceManagerHelper newInstance = PersistenceManagerHelper.NewInstance;
            Dictionary<OperationType, Unis.ORM.DbSql.SqlString[]> objectStandardEditSql = SqlConfigHelper.Instance.GetObjectStandardEditSql(objectDataMappingAttribute.MappingXmlFileName, optTypes);
            DataRow[] drsData = dsData.Tables[0].Select();
            if ((objectStandardEditSql.ContainsKey(OperationType.DeleteNotIn) && (foreingKeyValue != null)) && (foreingKeyValue != DBNull.Value))
            {
                EntityDbCommandInfo[] collection = newInstance.CreateDeleteNotInDbCommand(db, objectStandardEditSql[OperationType.DeleteNotIn], drsData, objectDataMappingAttribute.KeyName, foreingKeyValue);
                list.AddRange(collection);
            }
            new StringBuilder();
            foreach (DataRow row in drsData)
            {
                if (!ValueValidated.Instance.RowIsNull(row))
                {
                    DataRowState rowState = row.RowState;
                    if (rowState <= DataRowState.Added)
                    {
                        if ((rowState != DataRowState.Detached) && (rowState == DataRowState.Added))
                        {
                            if (objectStandardEditSql.ContainsKey(OperationType.Insert))
                            {
                                if ((!string.IsNullOrEmpty(objectDataMappingAttribute.ForeingKeyName) && (foreingKeyValue != null)) && (row.Table.Columns.Contains(objectDataMappingAttribute.ForeingKeyName) && (row[objectDataMappingAttribute.ForeingKeyName] == DBNull.Value)))
                                {
                                    row[objectDataMappingAttribute.ForeingKeyName] = foreingKeyValue;
                                }
                                foreach (DbCommand command in newInstance.CreateDbCommandByDataRow(db, objectStandardEditSql[OperationType.Insert], row))
                                {
                                    list.Add(new EntityDbCommandInfo(row, command));
                                }
                            }
                        }
                    }
                    else if ((rowState != DataRowState.Deleted) && (rowState == DataRowState.Modified))
                    {
                        if (objectStandardEditSql.ContainsKey(OperationType.Update))
                        {
                            foreach (DbCommand command2 in newInstance.CreateDbCommandByDataRow(db, objectStandardEditSql[OperationType.Update], row))
                            {
                                list.Add(new EntityDbCommandInfo(row, command2));
                            }
                        }
                    }
                }
            }
            return list;
        }

        public IList<EntityDbCommandInfo> CreateCmdsFromObjectDataList(IBaseRule baseRule, Database db, ObjectDataList dataList)
        {
            RuleSettingAttribute ruleSettingAtt = null;
            if (baseRule != null)
            {
                ruleSettingAtt = AttributeConfigHelper.Instance.GetRuleSettingAtt(baseRule);
            }
            if ((ruleSettingAtt != null) && (ruleSettingAtt.BaseDataType == null))
            {
                throw new APPException("业务类:" + baseRule.GetType().FullName + " 必须要先配置主表数据在单据中的类型值。", APPMessageType.SysErrInfo);
            }
            IEnumerable<ObjectDataInfo> canSaveAndOrder = dataList.GetCanSaveAndOrder();
            List<EntityDbCommandInfo> list = new List<EntityDbCommandInfo>();
            object foreingKeyValue = null;
            bool flag = false;
            PersistenceManagerHelper newInstance = PersistenceManagerHelper.NewInstance;
            foreach (ObjectDataInfo info in canSaveAndOrder)
            {
                if ((ruleSettingAtt != null) && (((int)info.DataInDocType) == ((int)ruleSettingAtt.BaseDataType)))
                {
                    if (ruleSettingAtt.GenerateKeyModel == GenerateKeyModel.OnDataSave)
                    {
                        EntityIdentityHelper.NewInstance.FillEntityIdentity(info.ObjectData);
                    }
                    foreingKeyValue = this.GetObjectKeyValue(baseRule, info);
                    flag = true;
                }
                else
                {
                    flag = false;
                }
                object objectData = info.ObjectData;
                if (objectData != null)
                {
                    if (!objectData.GetType().IsSubclassOf(typeof(BaseModel)))
                    {
                        if (!objectData.GetType().IsSubclassOf(typeof(DataSet)))
                        {
                            throw new DataTypeUnSupportException(objectData.GetType().FullName);
                        }
                        if (foreingKeyValue == null)
                        {
                            throw new APPException("在批量存储对象明细前必须先获取主表键值！", APPMessageType.SysErrInfo);
                        }
                        if (baseRule == null)
                        {
                            throw new APPException("通过CreateCmdsFromObjectDataList 执行DataSet时,业务对象不能为空", APPMessageType.SysErrInfo);
                        }
                        foreach (EntityDbCommandInfo info3 in this.CreateCmdsFromDataSet(db, baseRule, objectData as DataSet, foreingKeyValue, info.DataInDocType))
                        {
                            list.Add(info3);
                        }
                    }
                    else
                    {
                        DbCommand[] commandArray = null;
                        if (string.IsNullOrEmpty(info.ExecuteXmlCfgSqlName))
                        {
                            OperationType operationType = this.ConvertEntityStateToOperationType((objectData as BaseModel).EntityState);
                            if (operationType == OperationType.None)
                            {
                                continue;
                            }
                            commandArray = newInstance.GetDbCommand(db, objectData as BaseModel, operationType, info.SavePropertys);
                        }
                        else
                        {
                            commandArray = newInstance.GetDbCommand(db, objectData as BaseModel, info.ExecuteXmlCfgSqlName);
                        }
                        bool flag2 = false;
                        foreach (DbCommand command in commandArray)
                        {
                            EntityDbCommandInfo item = new EntityDbCommandInfo(objectData, command);
                            if (!flag2)
                            {
                                item.IsMainEntity = flag;
                                flag2 = true;
                            }
                            if (item.IsMainEntity && (info.DataState == ObjectDataState.Deleted))
                            {
                                item.OperationType = OperationType.Delete;
                            }
                            item.IsPartPropertyUpdate = (info.SavePropertys != null) && (info.SavePropertys.Length > 0);
                            list.Add(item);
                        }
                    }
                }
            }
            return list;
        }

        public object CreateNewEntity(IBaseRule baseRule, object dataInDocType)
        {
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            if (objectDataMappingAttribute == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            Type entityType = objectDataMappingAttribute.EntityType;
            if ((string.Compare(entityType.FullName, "System.Object", true) == 0) && (objectDataMappingAttribute.EntityType == null))
            {
                throw new APPException(string.Concat(new object[] { "业务类:", baseRule.GetType().FullName, " 中的:", dataInDocType.GetType(), " 的数据值:", dataInDocType.ToString(), " 在配置ObjectDataMapping时需要配置 EntityType" }), APPMessageType.SysErrInfo);
            }
            object rObj = Reflection.CreateObjectInstance(entityType);
            if (objectDataMappingAttribute.KeyIsSelfAdd)
            {
                string entityIdentity = EntityIdentityHelper.NewInstance.GetEntityIdentity();
                ModelMappingInfo mapinfo = new ModelMappingInfo();
                string strKey = AttMappingManager.Instance.GetPrimaryKey(rObj, ref mapinfo);
                Reflection.SetObjectProperty(rObj, string.IsNullOrEmpty(strKey) ? objectDataMappingAttribute.KeyName : strKey, entityIdentity);
            }
            if (rObj.GetType().IsSubclassOf(typeof(BaseModel)))
            {
                (rObj as BaseModel).EntityState = EntityState.New;
            }
            foreach (FieldPropertyInfo info2 in AttMappingManager.Instance.GetModelMappingInfo(entityType).FieldPropertys.Values)
            {
                if (info2.DefaultValue != null)
                {
                    entityType.GetProperty(info2.PropertyName).SetValue(rObj, info2.DefaultValue, null);
                }
            }
            return rObj;
        }

        public IList CreateNewEntityBatch(IBaseRule baseRule, object dataInDocType, int createCount)
        {
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            if (objectDataMappingAttribute == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            Type entityType = objectDataMappingAttribute.EntityType;
            if ((string.Compare(entityType.FullName, "System.Object", true) == 0) && (objectDataMappingAttribute.EntityType == null))
            {
                throw new APPException(string.Concat(new object[] { "业务类:", baseRule.GetType().FullName, " 中的:", dataInDocType.GetType(), " 的数据值:", dataInDocType.ToString(), " 在配置ObjectDataMapping时需要配置 EntityType" }), APPMessageType.SysErrInfo);
            }
            List<object> list = new List<object>();
            List<string> entityIdentity = null;
            if (objectDataMappingAttribute.KeyIsSelfAdd)
            {
                entityIdentity = EntityIdentityHelper.NewInstance.GetEntityIdentity(createCount);
            }
            for (int i = 0; i < createCount; i++)
            {
                object rObj = Reflection.CreateObjectInstance(entityType);
                //if (entityIdentity > 0)
                //{
                //    Reflection.SetObjectProperty(rObj, objectDataMappingAttribute.KeyName, entityIdentity++);
                //}
                Reflection.SetObjectProperty(rObj, objectDataMappingAttribute.KeyName, entityIdentity[i]);
                if (rObj.GetType().IsSubclassOf(typeof(BaseModel)))
                {
                    (rObj as BaseModel).EntityState = EntityState.New;
                }
                foreach (FieldPropertyInfo info2 in AttMappingManager.Instance.GetModelMappingInfo(entityType).FieldPropertys.Values)
                {
                    if (info2.DefaultValue != null)
                    {
                        entityType.GetProperty(info2.PropertyName).SetValue(rObj, info2.DefaultValue, null);
                    }
                }
                list.Add(rObj);
            }
            return list;
        }

        public int DeletedImmediate(IBaseRule baseRule, object dataInDocType, object key)
        {
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            if (objectDataMappingAttribute == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            Database db = DatabaseHelper.CreateDatabase();
            DbCommand[] commandArray = PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, objectDataMappingAttribute.MappingXmlFileName, "DeleteObject", new object[] { key });
            int num = 0;
            try
            {
                foreach (DbCommand command in commandArray)
                {
                    TraceEx.Write("正在执行:" + DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, command));
                    num = db.ExecuteNonQuery(command);
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                try
                {
                    foreach (DbCommand command2 in commandArray)
                    {
                        command2.Dispose();
                    }
                }
                catch
                {
                }
            }
            return num;
        }

        public object ExecuteScalar(string xmlFileName, string sqlName, params object[] parValues)
        {
            Database db = DatabaseHelper.CreateDatabase();
            DbCommand[] commandArray = PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, xmlFileName, sqlName, parValues);
            if (commandArray.Length != 1)
            {
                throw new SelectSqlXmlConfigException(xmlFileName, sqlName);
            }
            return db.ExecuteScalar(commandArray[0]);
        }

        public DataSet GetObjectAsDataSet(IBaseQueryRule baseRule, object dataInDocType, QueryParameterInfo[] parInfos, params object[] parValues)
        {
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            if (objectDataMappingAttribute == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            string sqlName = string.IsNullOrEmpty(objectDataMappingAttribute.XmlCfgSelectSqlName) ? "SelectObject" : objectDataMappingAttribute.XmlCfgSelectSqlName;
            QueryParameterMappings queryParamMapping = baseRule.QueryParamMapping;
            if (queryParamMapping == null)
            {
                queryParamMapping = SqlConfigHelper.Instance.GetSqlQueryParamMappings(objectDataMappingAttribute.MappingXmlFileName, sqlName);
            }
            string str2 = SqlShareHelper.Instance.QueryParametersToSqlString(queryParamMapping, parInfos);
            Database db = DatabaseHelper.CreateDatabase();
            ArrayList list = new ArrayList();
            if ((parValues != null) && (parValues.Length > 0))
            {
                foreach (object obj2 in parValues)
                {
                    list.Add(obj2);
                }
            }
            list.Add(str2);
            DbCommand[] commandArray = PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, objectDataMappingAttribute.MappingXmlFileName, sqlName, list.ToArray());
            if (commandArray.Length != 1)
            {
                throw new SelectSqlXmlConfigException(objectDataMappingAttribute.MappingXmlFileName, sqlName);
            }
            DbCommand dbCmd = commandArray[0];
            DataSet set = null;
            try
            {
                TraceEx.Write("正在执行:" + DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, dbCmd));
                set = db.ExecuteDataSet(dbCmd);
            }
            catch (Exception exception)
            {
                throw new DatabaseExecuteException("GetObjectAsDataSet 出错！", exception);
            }
            return set;
        }

        public T GetObjectByKey<T>(IBaseRule baseRule, object dataInDocType, object keyValue)
        {
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            if (objectDataMappingAttribute == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            Database db = DatabaseHelper.CreateDatabase();
            DbCommand[] commandArray = PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, objectDataMappingAttribute.MappingXmlFileName, "SelectByKey", new object[] { keyValue });
            if (commandArray.Length != 1)
            {
                throw new SelectSqlXmlConfigException(objectDataMappingAttribute.MappingXmlFileName, "SelectByKey");
            }
            DbCommand dbCmd = commandArray[0];
            Type t = typeof(T);
            if (string.Compare(t.FullName, "System.Object", true) == 0)
            {
                if (objectDataMappingAttribute.EntityType == null)
                {
                    throw new APPException(string.Concat(new object[] { "业务类:", baseRule.GetType().FullName, " 中的:", dataInDocType.GetType(), " 的数据值:", dataInDocType.ToString(), " 在配置ObjectDataMapping时需要配置 EntityType" }), APPMessageType.SysErrInfo);
                }
                t = objectDataMappingAttribute.EntityType;
            }
            bool flag = t.IsSubclassOf(typeof(BaseModel));
            ModelMappingInfo modelMappingInfo = AttMappingManager.Instance.GetModelMappingInfo(t);
            object rObj = Reflection.CreateObjectInstance(t);
            TraceEx.Write("正在执行:" + DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, dbCmd));
            IDataReader reader = db.ExecuteReader(dbCmd);
            try
            {
                DataTable schemaTable = reader.GetSchemaTable();
                while (reader.Read())
                {
                    foreach (FieldPropertyInfo info2 in modelMappingInfo.FieldPropertys.Values)
                    {
                        if ((schemaTable.Select(string.Format("ColumnName='{0}'", info2.FieldName)).Length > 0) && (reader[info2.FieldName] != DBNull.Value))
                        {
                            Reflection.SetObjectProperty(rObj, info2.PropertyName, reader[info2.FieldName]);
                        }
                    }
                    break;
                }
            }
            catch (Exception exception)
            {
                throw new DatabaseExecuteException("执行" + baseRule.GetType().FullName + "GetObjectByKey<T> 出错！", exception);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
            if (flag)
            {
                BaseModel model = rObj as BaseModel;
                model.EntityState = EntityState.Persistent;
            }
            return (T)rObj;
        }

        public object GetObjectKeyValue(IBaseRule baseRule, ObjectDataInfo dataInfo)
        {
            string keyName = null;
            if (dataInfo.DataInDocType != null)
            {
                ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInfo.DataInDocType);
                if (objectDataMappingAttribute != null)
                {
                    keyName = objectDataMappingAttribute.KeyName;
                }
            }
            bool flag = dataInfo.ObjectData.GetType().IsSubclassOf(typeof(BaseModel));
            if (string.IsNullOrEmpty(keyName) && flag)
            {
                ModelMapAttribute customAttribute = Attribute.GetCustomAttribute(dataInfo.ObjectData.GetType(), typeof(ModelMapAttribute)) as ModelMapAttribute;
                string[] primaryKeys = customAttribute.PrimaryKeys;
                if ((primaryKeys != null) && (primaryKeys.Length > 0))
                {
                    TraceEx.Assert(primaryKeys.Length > 1, "业务类：" + baseRule.GetType().FullName + " 主表对象的键值配置不能存在联合主键！");
                }
                keyName = primaryKeys[0];
            }
            if (string.IsNullOrEmpty(keyName))
            {
                throw new APPException("业务类：" + baseRule.GetType().FullName + " 的主表对象的主键信息没有配置！", APPMessageType.SysErrInfo);
            }
            if (flag)
            {
                return Reflection.GetObjectProperty(dataInfo.ObjectData, keyName);
            }
            if (!(dataInfo.ObjectData is DataRow))
            {
                throw new APPException("获取业务类：" + baseRule.GetType().FullName + " 的主表对象的键值有误！", APPMessageType.SysErrInfo);
            }
            return (dataInfo.ObjectData as DataRow)[keyName];
        }

        public List<T> GetObjects<T>(IBaseQueryRule baseRule, object dataInDocType, QueryParameterInfo[] parInfos, params object[] parValues)
        {
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            if (objectDataMappingAttribute == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            string sqlName = string.IsNullOrEmpty(objectDataMappingAttribute.XmlCfgSelectSqlName) ? "SelectObject" : objectDataMappingAttribute.XmlCfgSelectSqlName;
            QueryParameterMappings queryParamMapping = baseRule.QueryParamMapping;
            if (queryParamMapping == null)
            {
                queryParamMapping = SqlConfigHelper.Instance.GetSqlQueryParamMappings(objectDataMappingAttribute.MappingXmlFileName, sqlName);
            }
            string item = SqlShareHelper.Instance.QueryParametersToSqlString(queryParamMapping, parInfos);
            Type cfgEntityType = typeof(T);
            if (string.Compare(cfgEntityType.FullName, "System.Object", true) == 0)
            {
                if (objectDataMappingAttribute.EntityType == null)
                {
                    throw new APPException(string.Concat(new object[] { "业务类:", baseRule.GetType().FullName, " 中的:", dataInDocType.GetType(), " 的数据值:", dataInDocType.ToString(), " 在配置ObjectDataMapping时需要配置 EntityType" }), APPMessageType.SysErrInfo);
                }
                cfgEntityType = objectDataMappingAttribute.EntityType;
            }
            List<object> list = new List<object>();
            if ((parValues != null) && (parValues.Length > 0))
            {
                foreach (object obj2 in parValues)
                {
                    list.Add(obj2);
                }
            }
            list.Add(item);
            return DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<T>(cfgEntityType, objectDataMappingAttribute.MappingXmlFileName, sqlName, list.ToArray());
        }

        public List<T> GetObjectsByForeingKey<T>(IBaseRule baseRule, object dataInDocType, object mainKeyValue)
        {
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            if (objectDataMappingAttribute == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            Type cfgEntityType = typeof(T);
            if (string.Compare(cfgEntityType.FullName, "System.Object", true) == 0)
            {
                if (objectDataMappingAttribute.EntityType == null)
                {
                    throw new APPException(string.Concat(new object[] { "业务类:", baseRule.GetType().FullName, " 中的:", dataInDocType.GetType(), " 的数据值:", dataInDocType.ToString(), " 在配置ObjectDataMapping时需要配置 EntityType" }), APPMessageType.SysErrInfo);
                }
                cfgEntityType = objectDataMappingAttribute.EntityType;
            }
            return DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<T>(cfgEntityType, objectDataMappingAttribute.MappingXmlFileName, "GetByForeingKey", new object[] { mainKeyValue });
        }

        public DataSet GetObjectsByForeingKeyAsDs(IBaseRule baseRule, object dataInDocType, object mainKeyValue)
        {
            ObjectDataMappingAttribute objectDataMappingAttribute = AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType);
            if (objectDataMappingAttribute == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            Database db = DatabaseHelper.CreateDatabase();
            DbCommand[] commandArray = PersistenceManagerHelper.NewInstance.CreateDbCommandByXml(db, objectDataMappingAttribute.MappingXmlFileName, "GetByForeingKey", new object[] { mainKeyValue });
            if (commandArray.Length != 1)
            {
                throw new SelectSqlXmlConfigException(objectDataMappingAttribute.MappingXmlFileName, "GetByForeingKey");
            }
            DbCommand dbCmd = commandArray[0];
            DataSet set = null;
            try
            {
                TraceEx.Write("正在执行:" + DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, dbCmd));
                set = db.ExecuteDataSet(dbCmd);
            }
            catch (Exception exception)
            {
                throw new DatabaseExecuteException("GetObjectsByForeingKey 出错！", exception);
            }
            return set;
        }

        public object RefreshEntity(IBaseRule baseRule, object dataInDocType, object entity, params object[] parValues)
        {
            string keyPropertyName = string.Empty;
            object entityKeyValue = EntityDataHelper.Instance.GetEntityKeyValue(entity, out keyPropertyName);
            QueryParameterInfo[] parInfos = new QueryParameterInfo[] { new QueryParameterInfo(keyPropertyName, entityKeyValue, DataFilterConditions.Equal) };
            List<object> list = this.GetObjects<object>(baseRule, dataInDocType, parInfos, parValues);
            if ((list != null) && (list.Count != 0))
            {
                return list[0];
            }
            return null;
        }

        public int SaveDataSetImmediate(IBaseRule baseRule, object dataInDocType, DataSet dsData)
        {
            if (AttributeConfigHelper.Instance.GetObjectDataMappingAttribute(dataInDocType) == null)
            {
                throw new RequireConfigDataMappingException(dataInDocType);
            }
            Database db = DatabaseHelper.CreateDatabase();
            IList<EntityDbCommandInfo> list = this.CreateCmdsFromDataSet(db, baseRule, dsData, null, dataInDocType);
            if (list.Count == 0)
            {
                return 0;
            }
            int num = 0;
            try
            {
                foreach (EntityDbCommandInfo info in list)
                {
                    try
                    {
                        TraceEx.Write("正在执行:" + DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, info.DbCommand));
                        num += db.ExecuteNonQuery(info.DbCommand);
                        continue;
                    }
                    catch (Exception exception)
                    {
                        throw new DatabaseExecuteException("SaveDataSetImmediate 出错！", exception);
                    }
                }
                return num;
            }
            catch (DatabaseExecuteException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                try
                {
                    foreach (EntityDbCommandInfo info2 in list)
                    {
                        info2.DbCommand.Dispose();
                    }
                }
                catch
                {
                }
            }
            return num;
        }

        public int SaveObjectDataList(IBaseRule baseRule, ObjectDataList dataList)
        {
            if ((dataList == null) || (dataList.Count == 0))
            {
                return 0;
            }
            Database db = DatabaseHelper.CreateDatabase();
            IList<EntityDbCommandInfo> list = this.CreateCmdsFromObjectDataList(baseRule, db, dataList);
            if (list.Count == 0)
            {
                return 0;
            }
            int num = 0;
            List<DbCommand> list2 = new List<DbCommand>();
            try
            {
                foreach (EntityDbCommandInfo info in list)
                {
                    try
                    {
                        if (info.IsMainEntity)
                        {
                            EntityDistributedHelper.NewInstance.CheckEntityCanSave(info.DataEntity);
                            if (baseRule != null)
                            {
                                //ObjectSubmitHelper.NewInstance.CheckParentHasSubmit(db, baseRule, info.DataEntity);
                                //if (info.OperationType == OperationType.Delete)
                                //{
                                //    ObjectSubmitHelper.NewInstance.ObjectOwnerless(db, baseRule, info.DataEntity, LinkRestrictOption.CancelSubmit);
                                //}
                            }
                        }
                        TraceEx.Write("正在执行:" + DbCommandExecuteTrack.Instance.CommandToTrackMessage(db, info.DbCommand));
                        int num2 = db.ExecuteNonQuery(info.DbCommand);
                        if ((num2 > 0) && info.IsPartPropertyUpdate)
                        {
                            DbCommand saveLastModifiedDateCommand = EntityDistributedHelper.NewInstance.GetSaveLastModifiedDateCommand(db, info.DataEntity);
                            if (saveLastModifiedDateCommand != null)
                            {
                                db.ExecuteNonQuery(saveLastModifiedDateCommand);
                                list2.Add(saveLastModifiedDateCommand);
                            }
                        }
                        num += num2;
                        continue;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                return num;
            }
            catch (DatabaseExecuteException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                try
                {
                    foreach (EntityDbCommandInfo info2 in list)
                    {
                        info2.DbCommand.Dispose();
                    }
                    foreach (DbCommand command2 in list2)
                    {
                        command2.Dispose();
                    }
                }
                catch
                {
                }
            }
            return num;
        }

        // Properties
        public static ObjectEditHelper DefalutInstance
        {
            get
            {
                return Singleton<ObjectEditHelper>.InstanceObj;
            }
        }
    }
}
